package com.bosssoft.trainee.nontax.filter;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author Luo Wenlong
 * @date 2022-07-04 16:58
 * @description:授权过滤齐
 * @version: 1.0.0
 */
@Slf4j
//@Component
public class AuthenticationZuulFilter extends ZuulFilter {

    // 排除过滤的url
    private static final String LOGIN_URI = "/user/login";

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        log.info("zuul uri:{}", request.getRequestURI());
        //注册和登录接口不拦截，其他接口都要拦截校验 token
        if (request.getRequestURI().contains(LOGIN_URI)) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String token = request.getHeader("token");// 从 http 请求头中取出 token
        if (token == null) {
            token = request.getHeader("X-Token");
        }
        // 执行认证
        if (token == null) {
            throw new RuntimeException("无token - forbidden request this url ");
        }
        // 获取 token 中的 user id
        Integer userId;
        try {
            Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary("vueAdmin")).parseClaimsJws(token).getBody();
            userId = (Integer) claims.get("jti");
        } catch (JWTDecodeException j) {
            throw new RuntimeException("401");
        }
        return null;
    }
}
